﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Net;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page 
{
    private string strListen = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
        Response.Write(strListen);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string strUrl, strResult; 
        
        strUrl = "http://mp3.baidu.com/m?f=ms&tn=baidump3&ct=134217728&lf=&rn=&word="
            + HttpUtility.UrlEncode(txtContent.Text, Encoding.Default) + "&lm=2";
        
        strResult = ReadToString(strUrl);

        int startIndex = 0, httpIndex = 0, endIndex = 0;
        startIndex = strResult.IndexOf("请参照百度权利声明使用");
        strResult = strResult.Substring(startIndex);
        startIndex = strResult.IndexOf("<a target=");
        strResult = strResult.Substring(startIndex);
        httpIndex = strResult.IndexOf("http");

        endIndex = strResult.IndexOf("试听") - 2;

        strUrl = strResult.Substring(httpIndex, endIndex - httpIndex);
        strResult = ReadToString(strUrl);
        //startIndex = strResult.IndexOf("歌曲名");
        //strResult = strResult.Substring(startIndex, 600);
        //httpIndex = strResult.IndexOf("http");
        //endIndex = strResult.IndexOf("试听") - 2;

        //fileUrl = strResult.Substring(httpIndex, endIndex - httpIndex);
        int index1, index2;
        index1 = strResult.IndexOf("歌曲试听：</strong> <b>") + 18;
        index2 = strResult.IndexOf("...</b></span>");
        string str1 = strResult.Substring(0, index1);
        string str2 = strResult.Substring(index2);
        strListen = str1 + txtContent.Text + "  " + str2;
        Response.Write(strListen);
    }

    public string ReadToString(string strUrl)
    {
        string strResult;

        WebRequest wRequest = WebRequest.Create(strUrl);
        WebResponse wResponse = wRequest.GetResponse();
        Stream wStream = wResponse.GetResponseStream();
        StreamReader sr = new StreamReader(wStream, Encoding.GetEncoding("GB2312"));
        
        strResult = sr.ReadToEnd();
        wResponse.Close();

        return strResult;
    }
}
